const questionService = require('../../../services/question');
const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    tabActive: 0,
    subjects: ['语文', '数学', '英语'],
    subjectIndex: 0,
    questionTypes: [
      { id: 'all', name: '全部' },
      { id: 'single_choice', name: '单选题' },
      { id: 'multiple_choice', name: '多选题' },
      { id: 'true_false', name: '判断题' },
      { id: 'fill_blank', name: '填空题' },
      { id: 'short_answer', name: '简答题' }
    ],
    difficulties: [
      { id: 0, name: '全部' },
      { id: 1, name: '简单' },
      { id: 2, name: '较简单' },
      { id: 3, name: '中等' },
      { id: 4, name: '较难' },
      { id: 5, name: '困难' }
    ],
    questions: [],
    total: 0,
    currentPage: 1,
    pageSize: 10,
    loading: false,
    // 筛选条件
    filter: {
      subject: '语文',
      type: 'all',
      difficulty: 0,
      keyword: ''
    },
    // 删除相关
    showDeleteDialog: false,
    deleteQuestionId: '',
    // 选择相关
    showSelector: false,
    selectedQuestions: [],
    // 知识点
    knowledgeList: [],
    selectedKnowledge: [],
    showKnowledgePopup: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取知识点列表
    this.getKnowledgeList();
    // 获取试题列表
    this.getQuestionList();
  },

  /**
   * 切换标签页
   */
  onTabChange(event) {
    this.setData({
      tabActive: event.detail.index
    });
  },

  /**
   * 选择学科
   */
  onSubjectChange(event) {
    const subjectIndex = event.detail.value;
    const subject = this.data.subjects[subjectIndex];
    
    this.setData({
      subjectIndex,
      'filter.subject': subject,
      currentPage: 1
    });
    
    // 重新获取知识点列表
    this.getKnowledgeList();
    // 重新获取试题列表
    this.getQuestionList();
  },

  /**
   * 选择题型
   */
  onTypeChange(event) {
    const type = event.currentTarget.dataset.type;
    
    this.setData({
      'filter.type': type,
      currentPage: 1
    });
    
    this.getQuestionList();
  },

  /**
   * 选择难度
   */
  onDifficultyChange(event) {
    const difficulty = parseInt(event.currentTarget.dataset.difficulty);
    
    this.setData({
      'filter.difficulty': difficulty,
      currentPage: 1
    });
    
    this.getQuestionList();
  },

  /**
   * 搜索关键词
   */
  onSearch(event) {
    const keyword = event.detail;
    
    this.setData({
      'filter.keyword': keyword,
      currentPage: 1
    });
    
    this.getQuestionList();
  },

  /**
   * 获取知识点列表
   */
  async getKnowledgeList() {
    try {
      // 显示加载
      wx.showLoading({
        title: '加载中',
      });
      
      const subject = this.data.filter.subject;
      
      // 调用云函数获取知识点
      const result = await wx.cloud.callFunction({
        name: 'getKnowledgePoints',
        data: {
          subject
        }
      });
      
      // 隐藏加载
      wx.hideLoading();
      
      if (result.result.success) {
        this.setData({
          knowledgeList: result.result.knowledgePoints
        });
      } else {
        wx.showToast({
          title: result.result.message,
          icon: 'none'
        });
      }
    } catch (error) {
      // 隐藏加载
      wx.hideLoading();
      
      console.error('获取知识点失败', error);
      wx.showToast({
        title: '获取知识点失败',
        icon: 'none'
      });
    }
  },

  /**
   * 显示知识点选择弹窗
   */
  showKnowledgePopup() {
    this.setData({
      showKnowledgePopup: true
    });
  },

  /**
   * 关闭知识点选择弹窗
   */
  closeKnowledgePopup() {
    this.setData({
      showKnowledgePopup: false
    });
  },

  /**
   * 选择知识点
   */
  onKnowledgeChange(event) {
    this.setData({
      selectedKnowledge: event.detail
    });
  },

  /**
   * 确认知识点选择
   */
  confirmKnowledge() {
    this.setData({
      currentPage: 1,
      showKnowledgePopup: false
    });
    
    this.getQuestionList();
  },

  /**
   * 获取试题列表
   */
  async getQuestionList() {
    try {
      // 显示加载状态
      this.setData({
        loading: true
      });
      
      const { subject, type, difficulty, keyword } = this.data.filter;
      const { currentPage, pageSize, selectedKnowledge } = this.data;
      
      // 构建查询参数
      const params = {
        subject,
        page: currentPage,
        size: pageSize
      };
      
      // 添加可选参数
      if (type !== 'all') {
        params.type = type;
      }
      
      if (difficulty > 0) {
        params.difficulty = difficulty;
      }
      
      if (keyword) {
        params.keyword = keyword;
      }
      
      if (selectedKnowledge.length > 0) {
        params.knowledge = selectedKnowledge;
      }
      
      // 调用服务获取试题列表
      const result = await questionService.getQuestionList(params);
      
      // 隐藏加载状态
      this.setData({
        loading: false
      });
      
      if (result.success) {
        this.setData({
          questions: result.questions,
          total: result.total
        });
      } else {
        wx.showToast({
          title: result.message,
          icon: 'none'
        });
      }
    } catch (error) {
      // 隐藏加载状态
      this.setData({
        loading: false
      });
      
      console.error('获取试题列表失败', error);
      wx.showToast({
        title: '获取试题列表失败',
        icon: 'none'
      });
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    const { currentPage, pageSize, total } = this.data;
    
    // 计算总页数
    const totalPages = Math.ceil(total / pageSize);
    
    // 如果还有下一页，则加载下一页数据
    if (currentPage < totalPages) {
      this.setData({
        currentPage: currentPage + 1
      });
      
      this.getQuestionList();
    }
  },

  /**
   * 预览试题
   */
  previewQuestion(event) {
    const questionId = event.currentTarget.dataset.id;
    
    wx.navigateTo({
      url: `/pages/teacher/question-detail/index?id=${questionId}`
    });
  },

  /**
   * 编辑试题
   */
  editQuestion(event) {
    const questionId = event.currentTarget.dataset.id;
    
    wx.navigateTo({
      url: `/pages/teacher/question-edit/index?id=${questionId}`
    });
  },

  /**
   * 显示删除确认对话框
   */
  showDeleteConfirm(event) {
    const questionId = event.currentTarget.dataset.id;
    
    this.setData({
      showDeleteDialog: true,
      deleteQuestionId: questionId
    });
  },

  /**
   * 关闭删除确认对话框
   */
  closeDeleteDialog() {
    this.setData({
      showDeleteDialog: false,
      deleteQuestionId: ''
    });
  },

  /**
   * 确认删除试题
   */
  async confirmDelete() {
    try {
      const { deleteQuestionId } = this.data;
      
      if (!deleteQuestionId) {
        return;
      }
      
      // 显示加载
      wx.showLoading({
        title: '删除中',
      });
      
      // 调用服务删除试题
      const result = await questionService.deleteQuestion(deleteQuestionId);
      
      // 隐藏加载
      wx.hideLoading();
      
      if (result.success) {
        wx.showToast({
          title: '删除成功'
        });
        
        // 关闭对话框
        this.closeDeleteDialog();
        
        // 重新获取试题列表
        this.getQuestionList();
      } else {
        wx.showToast({
          title: result.message,
          icon: 'none'
        });
      }
    } catch (error) {
      // 隐藏加载
      wx.hideLoading();
      
      console.error('删除试题失败', error);
      wx.showToast({
        title: '删除试题失败',
        icon: 'none'
      });
    }
  },

  /**
   * 添加试题
   */
  addQuestion() {
    wx.navigateTo({
      url: '/pages/teacher/question-add/index'
    });
  },

  /**
   * 导入试题
   */
  importQuestions() {
    wx.navigateTo({
      url: '/pages/teacher/question-import/index'
    });
  },

  /**
   * 试题选择模式
   */
  toggleSelector() {
    this.setData({
      showSelector: !this.data.showSelector,
      selectedQuestions: []
    });
  },

  /**
   * 选择/取消选择试题
   */
  selectQuestion(event) {
    const questionId = event.currentTarget.dataset.id;
    const { selectedQuestions } = this.data;
    
    const index = selectedQuestions.findIndex(id => id === questionId);
    
    if (index >= 0) {
      // 取消选择
      selectedQuestions.splice(index, 1);
    } else {
      // 选择
      selectedQuestions.push(questionId);
    }
    
    this.setData({
      selectedQuestions
    });
  },

  /**
   * 批量删除试题
   */
  async batchDelete() {
    const { selectedQuestions } = this.data;
    
    if (selectedQuestions.length === 0) {
      wx.showToast({
        title: '请先选择试题',
        icon: 'none'
      });
      return;
    }
    
    // 显示确认对话框
    wx.showModal({
      title: '确认删除',
      content: `确定要删除选中的${selectedQuestions.length}道试题吗？`,
      success: async (res) => {
        if (res.confirm) {
          try {
            // 显示加载
            wx.showLoading({
              title: '删除中',
            });
            
            // 调用云函数批量删除试题
            const result = await wx.cloud.callFunction({
              name: 'batchDeleteQuestions',
              data: {
                questionIds: selectedQuestions
              }
            });
            
            // 隐藏加载
            wx.hideLoading();
            
            if (result.result.success) {
              wx.showToast({
                title: '删除成功'
              });
              
              // 退出选择模式
              this.setData({
                showSelector: false,
                selectedQuestions: []
              });
              
              // 重新获取试题列表
              this.getQuestionList();
            } else {
              wx.showToast({
                title: result.result.message,
                icon: 'none'
              });
            }
          } catch (error) {
            // 隐藏加载
            wx.hideLoading();
            
            console.error('批量删除试题失败', error);
            wx.showToast({
              title: '批量删除试题失败',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  /**
   * 加入试卷
   */
  addToPaper() {
    const { selectedQuestions } = this.data;
    
    if (selectedQuestions.length === 0) {
      wx.showToast({
        title: '请先选择试题',
        icon: 'none'
      });
      return;
    }
    
    // 将选中的试题存入全局变量
    app.globalData.selectedQuestions = selectedQuestions;
    
    // 跳转到创建试卷页面
    wx.navigateTo({
      url: '/pages/teacher/paper-create/index?from=question'
    });
  }
}) 